package com.dawn.module.hospital.service.chs.config;

import com.dawn.framework.common.enums.CommonStatusEnum;
import com.dawn.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.dawn.module.hospital.controller.admin.chs.config.vo.*;
import com.dawn.module.hospital.dal.dataobject.chs.config.ChsConfigDO;
import com.dawn.framework.common.pojo.PageResult;
import com.dawn.framework.common.pojo.PageParam;
import com.dawn.framework.common.util.object.BeanUtils;

import com.dawn.module.hospital.dal.mysql.chs.config.ChsConfigMapper;

import static com.dawn.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.dawn.module.hospital.enums.ErrorCodeConstants.*;

/**
 * 医保支付配置 Service 实现类
 *
 * @author mamba 4 left
 */
@Service
@Validated
public class ChsConfigServiceImpl implements ChsConfigService {

    @Resource
    private ChsConfigMapper chsConfigMapper;

    @Override
    public Long createChsConfig(ChsConfigSaveReqVO createReqVO) {
        // 插入
        ChsConfigDO chsConfig = BeanUtils.toBean(createReqVO, ChsConfigDO.class);
        chsConfigMapper.insert(chsConfig);
        // 返回
        return chsConfig.getId();
    }

    @Override
    public void updateChsConfig(ChsConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateChsConfigExists(updateReqVO.getId());
        // 更新
        ChsConfigDO updateObj = BeanUtils.toBean(updateReqVO, ChsConfigDO.class);
        chsConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteChsConfig(Long id) {
        // 校验存在
        validateChsConfigExists(id);
        // 删除
        chsConfigMapper.deleteById(id);
    }

    private void validateChsConfigExists(Long id) {
        if (chsConfigMapper.selectById(id) == null) {
            throw exception(CHS_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public ChsConfigDO getChsConfig(Long id) {
        return chsConfigMapper.selectById(id);
    }

    @Override
    public ChsConfigDO getChsConfig() {
        LambdaQueryWrapperX<ChsConfigDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eqIfPresent(ChsConfigDO::getStatus, CommonStatusEnum.ENABLE.getStatus());
        List<ChsConfigDO> configDOList = chsConfigMapper.selectList(queryWrapperX);
        if(configDOList.size() > 0){
            return configDOList.get(0);
        }else {
            throw exception(CHS_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public PageResult<ChsConfigDO> getChsConfigPage(ChsConfigPageReqVO pageReqVO) {
        return chsConfigMapper.selectPage(pageReqVO);
    }

}